import { ref } from 'vue';
import { getCookie, deleteCookie } from '../../utils/cookieUtils';

/**
 * 用户认证状态
 */
interface AuthState {
  isAuthenticated: boolean;
  token: string | null;
  userId: string | null;
}

// 初始状态
const initialState: AuthState = {
  isAuthenticated: false,
  token: null,
  userId: null
};

// 创建响应式状态
const authState = ref<AuthState>({...initialState});

/**
 * 认证状态管理
 */
export const authStore = {
  /**
   * 获取当前认证状态
   */
  getState: () => {
    // 每次获取状态时，确保从cookie中获取最新的token
    const token = getCookie('token');
    if (token && token !== authState.value.token) {
      authState.value.token = token;
      authState.value.isAuthenticated = true;
    }
    return authState.value;
  },
  
  /**
   * 设置认证状态
   * @param token 认证令牌
   * @param userId 用户ID
   */
  setAuth: (token: string, userId: string) => {
    authState.value = {
      isAuthenticated: true,
      token,
      userId
    };
    
    // 将userId存储到localStorage，token由服务端通过cookie设置
    localStorage.setItem('user_id', userId);
    // 设置isLoggedIn标志
    localStorage.setItem('isLoggedIn', 'true');
  },
  
  /**
   * 清除认证状态
   */
  clearAuth: () => {
    authState.value = {...initialState};
    
    // 清除localStorage中的认证信息
    localStorage.removeItem('user_id');
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('username');
    
    // 删除token cookie
    deleteCookie('token');
  },
  
  /**
   * 从cookie和localStorage恢复认证状态
   */
  restoreAuth: () => {
    const token = getCookie('token');
    const userId = localStorage.getItem('user_id');
    
    if (token && userId) {
      authState.value = {
        isAuthenticated: true,
        token,
        userId
      };
      return true;
    }
    
    return false;
  }
};